package com.liu.community.config;/*
 *@Author:Liu Xing-zhi
 *Description:   拦截器
 *Date:Crated in 18:08 2021/10/9
 */

import com.liu.community.enums.AdPosEnum;
import com.liu.community.pojor.Advertisement;
import com.liu.community.pojor.User;
import com.liu.community.server.AdvertisementService;
import com.liu.community.server.NotificationService;
import com.liu.community.server.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Service
public class SessionInterceptors implements HandlerInterceptor {
    @Autowired
    private UserService userService;
    @Autowired
    private NotificationService notificationService;
    @Autowired
    private AdvertisementService advertisementService;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //没有登录也可以查看导航广告
        for (AdPosEnum adPosEnum : AdPosEnum.values()) {
            String name = adPosEnum.name();
            Advertisement advertisement = advertisementService.queryAdvertisementMapByPos(name);
            request.getSession().setAttribute(name,advertisement);
        }


        Cookie[] cookies = request.getCookies();
        if (cookies != null && cookies.length != 0) {
            for (Cookie cookie : cookies) {
                if ("token".equals(cookie.getName())) {
                    //cookie相等
                    String token = cookie.getValue();
                    User user = userService.queryUserByToken(token);
                    if (user != null) {
                        request.getSession().setAttribute("user", user);
                        request.getSession().setAttribute("name", user.getName());
                        Integer unreadCount = notificationService.unreadCount(user.getId());
                        request.getSession().setAttribute("unreadCount",unreadCount);
                    }
                    //命中了，终止循环。
                    break;
                }
            }
        }
        return true;//放行
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
